from sqlalchemy.orm import Session
from app.models.issue import Issue
from app.schemas.issue import IssueCreate, IssueUpdate
from typing import List, Optional

# 获取问题通过ID
def get_issue(db: Session, issue_id: int):
    return db.query(Issue).filter(Issue.id == issue_id).first()

# 获取问题列表
def get_issues(db: Session, skip: int = 0, limit: int = 100, status: Optional[str] = None, category: Optional[str] = None, priority: Optional[str] = None):
    query = db.query(Issue)
    if status:
        query = query.filter(Issue.status == status)
    if category:
        query = query.filter(Issue.category == category)
    if priority:
        query = query.filter(Issue.priority == priority)
    return query.offset(skip).limit(limit).all()

# 创建问题
def create_issue(db: Session, issue: IssueCreate, submitter_id: int):
    db_issue = Issue(
        title=issue.title,
        description=issue.description,
        type=issue.type,
        category=issue.category,
        priority=issue.priority,
        submitter_id=submitter_id
    )
    db.add(db_issue)
    db.commit()
    db.refresh(db_issue)
    return db_issue

# 更新问题
def update_issue(db: Session, issue_id: int, issue: IssueUpdate):
    db_issue = db.query(Issue).filter(Issue.id == issue_id).first()
    if db_issue:
        if issue.title is not None:
            db_issue.title = issue.title
        if issue.description is not None:
            db_issue.description = issue.description
        if issue.type is not None:
            db_issue.type = issue.type
        if issue.category is not None:
            db_issue.category = issue.category
        if issue.priority is not None:
            db_issue.priority = issue.priority
        if issue.status is not None:
            db_issue.status = issue.status
        if issue.assignee_id is not None:
            db_issue.assignee_id = issue.assignee_id
        db.commit()
        db.refresh(db_issue)
    return db_issue

# 删除问题
def delete_issue(db: Session, issue_id: int):
    db_issue = db.query(Issue).filter(Issue.id == issue_id).first()
    if db_issue:
        db.delete(db_issue)
        db.commit()
    return db_issue